from PyQt5.QtCore import pyqtSignal, QObject
from PyQt5.QtWidgets import QLabel, QDockWidget, QWidget, QGridLayout
from logger import logger
from context import Component, context
from .sensor import SENSOR_CONFIG

@Component('cluster')
class Cluster(QObject):
    toggled = pyqtSignal(bool)

    def __init__(self):
        super().__init__()
        self.cluster_dock:QDockWidget = None
        
        # 创建内容控件
        self.content_widget = QWidget()
        # 设置网格布局
        self.grid_layout = QGridLayout(self.content_widget)
        self.grid_layout.setContentsMargins(10, 10, 10, 10)
        self.grid_layout.setSpacing(8)
        self.content_widget.setObjectName("cluster")
        self.values = {}

    def init_ui(self, cluster_dock):
        self.cluster_dock = cluster_dock
        self.cluster_dock.setWidget(self.content_widget)
        self.cluster_dock.setFeatures(
            QDockWidget.DockWidgetMovable |
            QDockWidget.DockWidgetClosable |
            QDockWidget.DockWidgetFloatable
        )
        self.__add_view()
        sensor = context.get('sensor')
        sensor.data_received.connect(self.__listen)

    def __add_view(self):
        row = 0
        for sensor_name, sensor_config in SENSOR_CONFIG.items():
            # 创建控件
            sensor_label = QLabel(sensor_name+":")
            sensor_label.setObjectName("sensor_label")
            
            sensor_value = QLabel(str(sensor_config['value']))
            sensor_value.setObjectName("sensor_value")
            
            sensor_unit = QLabel(sensor_config['unit'])
            sensor_unit.setObjectName("sensor_unit")
            
            self.values[sensor_config['id']] = sensor_value
            
            # 添加到网格布局
            self.grid_layout.addWidget(sensor_label, row, 0)  # 第一列放名称
            self.grid_layout.addWidget(sensor_value, row, 1)  # 第二列放值
            self.grid_layout.addWidget(sensor_unit, row, 2)   # 第三列放单位
            
            row += 1  # 下一行
        
        self.content_widget.setFixedSize(300, row*30)

    def __listen(self,id,val):
        self.values[id].setText(str(val))


    def toggle_cluster(self):
        logger.info("切换仪表视图")
        if self.cluster_dock.isVisible():
            self.cluster_dock.hide()
        else:
            self.cluster_dock.show()

